package cn.ulc.common.util;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class IFLYTEKHelper {
    private static final Log log = LogFactory.get();
    // 评测webapi接口地址
    private static final String WEBTTS_URL = "http://api.xfyun.cn/v1/service/v1/tts";
    // 测试应用ID
    private static final String TEST_APPID = "5c4bf8bf";//"5bfb45b2";
    // 测试接口密钥
    private static final String TEST_API_KEY = "72df4b9e7beec9c48d71029c32485609";//"9ca1668f07b6c2e72da89da1901a5f8c";

    public static String getMp3(String orderNumber, BigDecimal amount) {
        String aue = "lame";
        Map<String, String> header = null;
        try {
            header = getHeader("audio/L16;rate=16000", aue, "xiaoyan", "40", "100", "", "text", "50");
            String text = "系统到账" + amount + "元";
            Map<String, Object> resultMap = HttpUtil.doMultiPost(WEBTTS_URL, header, "text=" + text);
            for(String key : resultMap.keySet()) {
                log.info("Key :" + key + " | value :" + resultMap.get(key));
            }
            // 合成成功
            if ("audio/mpeg".equals(resultMap.get("Content-Type"))) {
                File file = FileUtil.save("/opt/mp3/", resultMap.get("sid") + ".mp3", (byte[]) resultMap.get("body"));
                log.info("mp3Path : %s" , file.getPath());
                String path = AliyunOssFileUtil.uploadPublicFile(file , orderNumber , "mp3/");
                //上传到阿里云以后，删除本地文件
                file.delete();
                return path;
            } else { // 合成失败
                System.out.println("失败===>"+resultMap.get("body").toString());
            }
        } catch (Exception e) {
            log.info("失败了===> %s",e.getMessage());
            e.printStackTrace();
        }
       return null;
    }


    /**
     * 组装http请求头
     *
     * @param aue
     * @return
     * @throws UnsupportedEncodingException
     */
    private static Map<String, String> getHeader(String auf, String aue, String voiceName, String speed, String volume, String engineType, String textType, String pitch) throws UnsupportedEncodingException, Exception {
        String curTime = System.currentTimeMillis() / 1000L + "";
        String param = "{\"auf\":\"" + auf + "\"";
        if (!StringUtils.isBlank(aue)) {
            param += ",\"aue\":\"" + aue + "\"";
        }
        if (!StringUtils.isBlank(voiceName)) {
            param += ",\"voice_name\":\"" + voiceName + "\"";
        }
        if (!StringUtils.isBlank(speed)) {
            param += ",\"speed\":\"" + speed + "\"";
        }
        if (!StringUtils.isBlank(volume)) {
            param += ",\"volume\":\"" + volume + "\"";
        }
        if (!StringUtils.isBlank(pitch)) {
            param += ",\"pitch\":\"" + pitch + "\"";
        }
        if (!StringUtils.isBlank(engineType)) {
            param += ",\"engine_type\":\"" + engineType + "\"";
        }
        if (!StringUtils.isBlank(textType)) {
            param += ",\"text_type\":\"" + textType + "\"";
        }
        param += "}";

        String paramBase64 = new String(Base64.encodeBase64(param.getBytes("UTF-8")));
        String checkSum = DigestUtils.md5Hex(TEST_API_KEY + curTime + paramBase64);
        Map<String, String> header = new HashMap<String, String>();
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        header.put("X-Param", paramBase64);
        header.put("X-CurTime", curTime);
        header.put("X-CheckSum", checkSum);
        header.put("X-Real-Ip", "192.168.1.102");
        header.put("X-Appid", TEST_APPID);
        System.out.println(header);
        return header;
    }
}
